#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import requests
import os
import sys
import shutil


def GenURL(fanhao: str):
    fanhao_lower = fanhao.lower()
    fanhao_lower_split = fanhao_lower.split("-")
    fanhao_lower_head = fanhao_lower_split[0]
    fanhao_lower_tail = fanhao_lower_split[1]
    fanhao_lower_minus = fanhao_lower
    fanhao_lower = fanhao_lower.replace("-", "")
    url = ""
    if fanhao.startswith(("ABP", "BGN", "CHN", "DCX", "BLO", "TDT", "DOM")):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/118' + fanhao_lower + "/118" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("AVOP"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/1' + fanhao_lower + "so/1" + fanhao_lower + 'sopl.jpg'
    elif fanhao.startswith("SACE"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/1' + fanhao_lower + "re/1" + fanhao_lower + 'repl.jpg'
    elif fanhao.startswith(("DVDES", "FSET", "HUNT", "LADY", "NHDTB", "NTR-", "SDDE", "SDNM", "SDMT", "SDMS")):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/1' + fanhao_lower + "/1" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("WSS"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/2' + fanhao_lower + "/2" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("BOIN"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/436' + fanhao_lower + "/436" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("KMD"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/161' + fanhao_lower + "/161" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("BBA"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/36' + fanhao_lower + "/36" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("EKDV"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/49' + fanhao_lower + "/49" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("DV-"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/53' + fanhao_lower + "/53" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("MCSR"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/57' + fanhao_lower + "/57" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("SHE"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/59' + fanhao_lower + "/59" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("XV-"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/60' + fanhao_lower + "/60" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith(("REAL", "SCPX", "UMSO", "XRW", "BAZX", "MDB")):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/84' + fanhao_lower + "/84" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith(("PPT", "SGA", "SIV", "SLG", "TEM", "JBS", "DKS", "RDT")):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/118' + fanhao_lower + "/118" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("GVG"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/13' + fanhao_lower + "/13" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("SKMJ"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_1324' + fanhao_lower + "/h_1324" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("HONB"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_1133' + fanhao_lower + "/h_1133" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("HZGD"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_1100' + fanhao_lower + "/h_1100" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("KAGH"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_970' + fanhao_lower + "/h_970" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("ZEX"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_720' + fanhao_lower + "/h_720" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("SW-"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_635' + fanhao_lower + "/h_635" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("AOZ"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_308' + fanhao_lower + "/h_308" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("TKI"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_286' + fanhao_lower + "/h_286" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith(("HNB", "DMAT")):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_254' + fanhao_lower + "/h_254" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("SAMA"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_244' + fanhao_lower + "/h_244" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("SKD"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_179' + fanhao_lower + "/h_179" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("UPSM"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_150' + fanhao_lower + "/h_150" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("YSN"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_127' + fanhao_lower + "/h_127" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("MXGS"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/h_068' + fanhao_lower + "/h_068" + fanhao_lower + 'pl.jpg'
    elif fanhao.startswith("IBW"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/504' + fanhao_lower + "z/504" + fanhao_lower + 'zpl.jpg'
    elif fanhao.startswith(("GAOR", "URPW", "DVAJ", "APAA", "YMDD")):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/' + fanhao_lower + "so/" + fanhao_lower + 'sopl.jpg'
    elif fanhao.startswith("AUKG"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/23' + fanhao_lower + "so/23" + fanhao_lower + 'sopl.jpg'
    elif fanhao.startswith("MIDE-377"):
        url = 'http://pics.dmm.co.jp/mono/movie/adult/9' + fanhao_lower + "/9" + fanhao_lower + 'pl.jpg'
    # elif fanhao.startswith("219VRTM"):
    #     url = 'https://image.mgstage.com/images/vrproduce/' + fanhao_lower_head + "/" + fanhao_lower_tail + "/pb_e_" + fanhao_lower_minus + '.jpg'
    # elif fanhao.startswith("300MAAN"):
    #     url = 'https://image.mgstage.com/images/prestigepremium/' + fanhao_lower_head + "/" + fanhao_lower_tail + "/pb_e_" + fanhao_lower_minus + '.jpg'
    # elif fanhao.startswith("200GANA"):
    #     url = 'https://image.mgstage.com/images/nanpatv/' + fanhao_lower_head + "/" + fanhao_lower_tail + "/pb_e_" + fanhao_lower_minus + '.jpg'
    # elif fanhao.startswith("259LUXU"):
    #     url = 'https://image.mgstage.com/images/luxutv/' + fanhao_lower_head + "/" + fanhao_lower_tail + "/pb_e_" + fanhao_lower_minus + '.jpg'
    # elif fanhao.startswith("261ARA"):
    #     url = 'https://image.mgstage.com/images/ara/' + fanhao_lower_head + "/" + fanhao_lower_tail + "/pb_e_" + fanhao_lower_minus + '.jpg'
    else:
        url = 'http://pics.dmm.co.jp/mono/movie/adult/' + fanhao_lower + "/" + fanhao_lower + 'pl.jpg'
    return url


def GetCensoredPic(fanhao: str, base_path: str):
    if os.path.exists(base_path + "/" + fanhao + "/" + fanhao + ".jpg"):
        return "exists"
    else:
        url = GenURL(fanhao)
        r = requests.get(url)
        if r.status_code == 200:
            # if not os.path.exists(base_path + "/" + fanhao):
            #     os.makedirs(base_path + "/" + fanhao)
            with open(base_path + "/" + fanhao + "/" + fanhao + ".jpg", 'wb') as fd:
                for chunk in r.iter_content(1024 * 1024):
                    fd.write(chunk)
                fd.close()
            print(fanhao + ".jpg downloaded.")
            jpg_size = os.path.getsize(base_path + "/" + fanhao + "/" + fanhao + ".jpg")
            if (jpg_size >= 10000):
                shutil.move(base_path + "/" + fanhao, base_path + "/Censored/")
                print(fanhao + ".jpg is valid.")
                return "valid"
            else:
                # shutil.rmtree(base_path + "/" + fanhao, ignore_errors=True)
                os.remove(base_path + "/" + fanhao + "/" + fanhao + ".jpg")
                print(fanhao + ".jpg is invalid.")
                return "invalid"
        else:
            print("Web Error.")
            return None


def GetUncensoredPic(fanhao: str, base_path: str):
    if os.path.exists(base_path + "/" + fanhao + "/" + fanhao + ".jpg"):
        return "exists"
    else:
        fanhao_lower = fanhao.lower()
        fanhao_lower_minus = fanhao_lower
        url = 'https://imgs.aventertainments.com/new/bigcover/dvd1' + fanhao_lower_minus + '.jpg'
        r = requests.get(url)
        if r.status_code == 200:
            with open(base_path + "/" + fanhao + "/" + fanhao + ".jpg", 'wb') as fd:
                for chunk in r.iter_content(1024 * 1024):
                    fd.write(chunk)
                fd.close()
            print(fanhao + ".jpg downloaded.")
            jpg_size = os.path.getsize(base_path + "/" + fanhao + "/" + fanhao + ".jpg")
            if (jpg_size >= 10000):
                shutil.move(base_path + "/" + fanhao, base_path + "/Uncensored/")
                print(fanhao + ".jpg is valid.")
                return "valid"
            else:
                os.remove(base_path + "/" + fanhao + "/" + fanhao + ".jpg")
                print(fanhao + ".jpg is invalid.")
                return "invalid"
        else:
            print("Cannnot find " + fanhao + " in new.")
            result = GetOldUncensoredPic(fanhao, base_path)
            return result


def GetOldUncensoredPic(fanhao: str, base_path: str):
    if os.path.exists(base_path + "/" + fanhao + "/" + fanhao + ".jpg"):
        return "exists"
    else:
        fanhao_lower = fanhao.lower()
        fanhao_lower_minus = fanhao_lower
        url = 'https://imgs.aventertainments.com/archive/bigcover/dvd1' + fanhao_lower_minus + '.jpg'
        r = requests.get(url)
        if r.status_code == 200:
            with open(base_path + "/" + fanhao + "/" + fanhao + ".jpg", 'wb') as fd:
                for chunk in r.iter_content(1024 * 1024):
                    fd.write(chunk)
                fd.close()
            print(fanhao + ".jpg downloaded.")
            jpg_size = os.path.getsize(base_path + "/" + fanhao + "/" + fanhao + ".jpg")
            if (jpg_size >= 10000):
                shutil.move(base_path + "/" + fanhao, base_path + "/Uncensored/")
                print(fanhao + ".jpg is valid.")
                return "valid"
            else:
                os.remove(base_path + "/" + fanhao + "/" + fanhao + ".jpg")
                print(fanhao + ".jpg is invalid.")
                return "invalid"
        else:
            print("Cannot find " + fanhao + " in archive either.")
            return None


if __name__ == '__main__':
    count = [0, 0, 0, 0]

    # infile = open("/Users/genesis/Documents/AV_Pic/list1.txt", "r")
    parent_path = sys.argv[1]
    dirlist = os.listdir(parent_path)
    for dir in dirlist:
        if os.path.isfile(os.path.join(parent_path, dir)):
            os.mkdir(parent_path + "/" + dir.split(".")[0])
            shutil.move(parent_path + "/" + dir, parent_path + "/" + dir.split(".")[0] + "/")
        if dir != "Censored" and dir != "Uncensored":
            if dir.startswith(
                    (
                            "ENBD", "GUILD", "HEY", "KHY", "MCB3DBD", "MKBD", "MKD", "RED", "SIRO", "BT-", "CZBD",
                            "LAF", "MCDV", "BD-", "KG-", "HEYZO", "CWDV", "EMP", "KP-",
                            "CWP", "RED", "SKY", "SMD", "PT-", "S2M", "LL-", "MCB", "TRP", "RHJ", "SMDV", "SHX", "MXX",
                            "DRC", "DSAM", "LLDV", "MMDV", "SSDV", "MD-", "MINA", "SSKJ", "DT-", "TRG", "CDRP")):
                result = GetUncensoredPic(dir.split(".")[0], parent_path)
            else:
                result = GetCensoredPic(dir.split(".")[0], parent_path)
            if result == "exists":
                count[0] += 1
            elif result == "valid":
                count[1] += 1
            elif result == "invalid":
                count[2] += 1
            else:
                count[3] += 1
    # for line in infile:
    #     line = line.rstrip()
    #     result = GetPic(line, "/Users/genesis/Documents/AV_Pic")
    #     if result == "exists":
    #         count[0] += 1
    #     elif result == "valid":
    #         count[1] += 1
    #     elif result == "invalid":
    #         count[2] += 1
    #     else:
    #         count[3] += 1
    # infile.close()
    print("Exist: " + str(count[0]) + "; Valid: " + str(count[1]) + "; Invalid: " + str(count[2]) + "; Other: " + str(
        count[3]) + ".")
